using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ProtocToCSharp
{
    public abstract class ArgDictionary<T>
    {
        
        public ArgDictionary( string splitKey, string[] args)
        {
            Dictionary<string, string> keyvalue = new Dictionary<string, string>();
            for (int i = 0; i < args.Length; i++)
            {
                int index = args[i].IndexOf(splitKey);
                if (index >=0)
                {
                    string key = args[i].Substring(0, index);
                    string value = args[i].Substring(index + 1);

                    if (!keyvalue.ContainsKey(key))
                    {
                        keyvalue.Add(key, value);
                    }
                }
     
            }
            Type t = typeof(T);
            t.GetProperties().ToList().ForEach(p =>
            {
                object[] atts = p.GetCustomAttributes(typeof(ArgObjectAttribute), false);
                if (atts.Length>0 && keyvalue.TryGetValue(((ArgObjectAttribute)atts[0]).Key,out string value))
                {
                    object val = ArgValueConvert(value, p.PropertyType);

                    p.SetValue(this, val, null);
                }
                else if(atts.Length > 0)
                {
                   // object val = ArgValueConvert(((ArgObjectAttribute)atts[0]).DefaultValue, p.PropertyType); 

                   // p.SetValue(this, val, null);
                }

            });



        }
    
        object ArgValueConvert(string value, Type type)
        {
            try
            {
                if (type == typeof(DirectoryInfo))
                {

                    return new DirectoryInfo(value);

                }
                else if (type == typeof(FileInfo))
                {
                    return new FileInfo(value);


                }
                else if (type == typeof(bool))
                {
                    try
                    {
                        return Convert.ToBoolean(value);

                    }
                    catch (Exception)
                    {

                        return false;
                    }
                
                }
            }
            catch (Exception)
            {

            }
            return null;

        }


    }


    public class ArgObjectAttribute : Attribute
    {
        public string Key { get; set; }
        public ArgObjectAttribute(string Key)
        {
            this.Key = Key;
        }
 
    }

   



    enum ArgType
    {
        DirectoryInfo,
        FileInfo,
        Bool

    }
}
